package com.example.flutter_encryption;

import androidx.annotation.NonNull;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

import java.util.Map;

/** FlutterEncryptionPlugin */
public class FlutterEncryptionPlugin implements FlutterPlugin, MethodCallHandler {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private MethodChannel channel;

  @Override
  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
    channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "flutter_encryption");
    channel.setMethodCallHandler(this);
  }

  @Override
  public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
    if (call.method.equals("getPlatformVersion")) {
      result.success("Android " + android.os.Build.VERSION.RELEASE);
    } else if (call.method.equals("encode")) {
      Map<String, String> map = (Map<String, String>) call.arguments;
      try {
        result.success(Des3.encode(map.get("s"), map.get("k")));
      } catch (Exception e) {
        e.printStackTrace();
        result.success("error");
      }
    } else if (call.method.equals("decode")) {
      Map<String, String> map = (Map<String, String>) call.arguments;
      try {
        result.success(Des3.decode(map.get("s"), map.get("k")));
      } catch (Exception e) {
        e.printStackTrace();
        result.success("error");
      }
    } else if (call.method.equals("encode2")) {
      Map<String, String> map = (Map<String, String>) call.arguments;
      DesUtil des = new DesUtil(map.get("k"), "01234567");
      try {
        result.success(des.encode(map.get("s")));
      } catch (Exception e) {
        e.printStackTrace();
        result.success("error");
      }
    } else if (call.method.equals("decode2")) {
      Map<String, String> map = (Map<String, String>) call.arguments;
      DesUtil des = new DesUtil(map.get("k"), "01234567");
      try {
        result.success(des.decode(map.get("s")));
      } catch (Exception e) {
        e.printStackTrace();
        result.success("error");
      }
    } else {
      result.notImplemented();
    }
  }

  @Override
  public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
    channel.setMethodCallHandler(null);
  }
}
